<?php
require_once("lib.php");

if (!isset($_SESSION["measure"])) {
    $_SESSION["measure"] = "f";
}

if (isset($_GET["f"])) {
    $_SESSION["measure"] = "f";
}

if (isset($_GET["m"])) {
    $_SESSION["measure"] = "m";
}

$unitOfMeasure = "ft";
if ($_SESSION["measure"] == "m") {
    $unitOfMeasure = "m";
}

$info = "";
if (isset($_GET["t"])) {
	$trackID = $_GET["t"];

    $measureToggle = '<a href="?t=' . $trackID . '&f"><span class="label label-warning">meters</span></a>';
    if ($_SESSION["measure"] == "f") {
        $measureToggle = '<a href="?t=' . $trackID . '&m"><span class="label label-info">feet</span></a>';
    }

    // Fetch basic data
	$stmt = $db->prepare("SELECT t.id AS trackID, t.tableName AS tableName, t.trackName AS trackName, t.userDescr AS trackDescr, t.userPhotoAlbumURL AS photoURL, t.userHikeLogURL AS hikeLogURL, UNIX_TIMESTAMP(t.trackDate) AS trackDate, GROUP_CONCAT(DISTINCT tt.trackTag ORDER BY tt.trackTag SEPARATOR '||') AS tags FROM track_tables_info t LEFT JOIN track_tags_link ttl ON ttl.tracksID = t.id LEFT JOIN track_tags tt ON tt.id = ttl.trackTagID WHERE t.id = :trackID GROUP BY t.id ORDER BY trackDate DESC");
    if ($stmt->execute(array("trackID" => $trackID))) {
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $tableName = $row["tableName"];
        $trackName = $row["trackName"]; 
        $trackDate = $row["trackDate"]; 
        $trackDescr = ($row["trackDescr"] == "" ? "(not set)" : $row["trackDescr"]);
        $trackPhotlAlbumURL = ($row["photoURL"] == "" ? "(not set)" : $row["photoURL"]);
        $trackHikeLogURL = ($row["hikeLogURL"] == "" ? "(not set)" : $row["hikeLogURL"]);
        $tags = $row["tags"];
        $trackPhotlAlbumURL = (filter_var($trackPhotlAlbumURL, FILTER_VALIDATE_URL) ? sprintf("<a target=\"_new\" href=\"%s\">%s</a>", $trackPhotlAlbumURL, $trackPhotlAlbumURL) : $trackPhotlAlbumURL);
        $trackHikeLogURL = (filter_var($trackHikeLogURL, FILTER_VALIDATE_URL) ? sprintf("<a target=\"_new\" href=\"%s\">%s</a>", $trackHikeLogURL, $trackHikeLogURL) : $trackHikeLogURL);
        $tagList = "";
        foreach (explode("||", $tags) as $tag) {
            $tagList .= "<span class=\"label label-info\">$tag</span>&nbsp;";
        }
        $tagList = ($tagList == "" ? "(none set)" : $tagList);
    }

    $stmt = $db->prepare("SELECT COUNT(OGR_FID) as count FROM :tableName");
    $count = "";
    if ($stmt->execute(array("tableName" => $tableName))) {
        $rowCount = $stmt->rowCount();
        $count = $rowCount["count"];
    }

	$info .= "<dt>Track Name</dt><dd>$trackName</dd>";
	$info .= "<dt>Track Date</dt><dd>$trackDate</dd>";
	$info .= "<dt>Track Points</dt><dd>$count</dd>";
	$info .= "<dt>Track Description</dt><dd>$trackDescr</dt>";
	$info .= "<dt>Track Photo Album</dt><dd>$trackPhotlAlbumURL</dt>";
	$info .= "<dt>Track Hike Log</dt><dd>$trackHikeLogURL</dt>";
	$info .= "<dt>Track Tags</dt><dd>$tagList</dt>";

	$stmt = $db->prepare("SELECT MAX(ele) as maxElev, MIN(ele) as minElev, TIMESTAMPDIFF(SECOND, MIN(time), MAX(time)) as timeDiff FROM :tableName");
    if ($stmt->execute(array("tableName" => $tableName))) {
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $maxElev = ($_SESSION["measure"] == "f" ? round(Util::meters2feet($row["maxElev"]), 2) : round($rows["maxElev"], 2));
        $minElev = ($_SESSION["measure"] == "f" ? round(Util::meters2feet($row["minElev"]), 2) : round($row["minElev"], 2));
        $elevDiff = $req["rows"][0]["maxElev"] - $rows["minElev"];
        $elevDiff = ($_SESSION["measure"] == "f" ? round(Util::meters2feet($elevDiff), 2) : round($elevDiff, 2));
        $timeDiff = $rows["timeDiff"];
        $info .= "<dt>Maximum Elevation</dt><dd>$maxElev $unitOfMeasure</dd>"; 
        $info .= "<dt>Minimum Elevation</dt><dd>$minElev $unitOfMeasure</dd>"; 
        $info .= "<dt>Elevation Change</dt><dd>$elevDiff $unitOfMeasure</dd>";
        $duration = Util::seconds2HumanTime($timeDiff);
        $info .= sprintf("<dt>Hike duration</dt><dd>%02d:%02d:%02d</dd>", $duration["hours"], $duration["minutes"], $duration["seconds"]);
    }


} else {
	header("Location: index.php");
}

$editTrack = "";
if ($_SESSION["authed"]) {
    $editTrack = "<li class=\"divider-vertical\"></li><li><a href=\"editTrack.php?t=$trackID\">Edit Track</a></li>";
}

$directLink = base64_encode(json_encode(Array("multitracks" => Array($trackID))));

$measure = $_SESSION["measure"];
$htmlTitle = "Hikes and Things: track details";
echo <<<CONTENT
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>$htmlTitle</title>
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
        <link href="style.css" rel="stylesheet">
        $analytics
    </head>
    <body>
        <div class="navbar navbar-static">
            <div class="navbar-inner">
                <div class="container" style="width: auto;">
                    <a class="brand" href="#">Track Details</a>
                    <ul class="nav" role="navigation">
                        <li class="divider-vertical"></li>
                        <li><a href="index.php">Tracks</a></li>
                        <li class="divider-vertical"></li>
                        <li><a href="map.php?tracks=$directLink">Map</a>
                        $editTrack
                    </ul>
                    <ul class="nav pull-right">
                        <li class="divider-vertical"></li>
                        <li>$measureToggle</li>
                        <li class="divider-vertical"></li>
                        <li>$logInOut</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container-fluid">
            <div class="row-fluid">
                <div class="span5">
                    <div class="well">  
                        <dl class="dl-horizontal">
                            $info
                        </dl>
                    </div>
                </div>
            <div class="span7">
                <div class="well">
                    <div id="_elevationPlot" data-trackname="$trackName" data-trackid=$trackID" data-measure="$measure">
                        <p class="center">Loading elevation data...</p>
                    </div>
                </div>
            </div>
        </div>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script>
            google.load('visualization', '1', {'packages':['corechart']});
        </script>
        <script src="jquery-1.9.1.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
        <script src="elevationPlot.js"></script>
    </body>
</html>
CONTENT;
?>
